package br.ufrn.imd.classificados.activity;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import br.ufrn.imd.classificados.tasks.ApiPutTask;
import br.ufrn.imd.imd0023_classificados.R;

import com.actionbarsherlock.app.SherlockActivity;

public class EditarAnuncioActivity extends SherlockActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.editar_anuncio);

		Button salvarAnuncioButton = (Button) findViewById(R.id.salvarAnuncioButton);
		salvarAnuncioButton.setOnClickListener(new OnClickListener() {
	
			@Override
			public void onClick(View v) {
				sendPut(
					((TextView) findViewById(R.id.idAnuncio)).getText().toString(),
					((EditText) findViewById(R.id.tituloAnuncio)).getText().toString(),
					((EditText) findViewById(R.id.descricaoAnuncio)).getText().toString(),
					((EditText) findViewById(R.id.valorAnuncio)).getText().toString(),
					((RadioButton) findViewById(R.id.radio0)).isChecked()
				);

				Toast.makeText(getBaseContext(), "Item foi salvo", Toast.LENGTH_LONG).show();
				finish();
			}
		});
	}
	
	private void sendPut(String id, String title, String description, String value, boolean buying) {
	    JSONObject jsonObj = new JSONObject();

	    try {
	    	jsonObj.put("id", id);
	    	jsonObj.put("title", title);
	    	jsonObj.put("description", description);
	    	jsonObj.put("value", value);
	    	jsonObj.put("selling", (buying ? "false" : "true"));
	    } catch (JSONException e) {
	    	e.printStackTrace();
	    	Log.i("JSON Exception", e + "");
	    }

	    new ApiPutTask("items").execute(jsonObj);
	}
}
